package com.dpteam.service.impl;

import com.dpteam.bean.UserInfo;
import com.dpteam.dao.RoleDao;
import com.dpteam.dao.UserDao;
import com.dpteam.model.Role;
import com.dpteam.model.User;
import com.dpteam.service.UserManageService;
import com.dpteam.util.Constant;
import com.dpteam.util.Page;
import com.dpteam.util.TransformUtil;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by xwh on 2016/1/11.
 */
@Service
@Transactional
public class UserManageServiceImpl implements UserManageService {

    @Resource
    private UserDao userDao;

    @Resource
    private RoleDao roleDao;

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public int addUser(UserInfo userInfo) {
        logger.info("addUser");
        if (userInfo == null) {
            return 0;
        }
        User user = new User();
        user.setName(userInfo.getName());
        user.setEmail(userInfo.getEmail());
        user.setAccount(userInfo.getAccount());
        user.setPassword(userInfo.getPassword());
        //user.setIDCard();
        user.setPhone(userInfo.getPhone());
        user.setGender(userInfo.getGenderCode());
        Role role = roleDao.get(Role.class, userInfo.getRoleId());
        if (role == null) {
            return 0;
        }
        user.setRole(role);
        LocalDateTime localDateTime = LocalDateTime.now();
        if (localDateTime == null) {
            return 0;
        }
        user.setOnJobTime(localDateTime);
        return (int) userDao.save(user);
    }

    @Override
    public int deleteUserById(Integer userId) {
        logger.info("deleteUserById");
        userDao.deleteById(userId);
        return 1;
    }

    @Override
    public int updateUserById(UserInfo userInfo) {
        logger.info("updateUserById");
        if (userInfo == null) {
            return 0;
        }
        User user = new User();
        user.setName(userInfo.getName());
        user.setEmail(userInfo.getEmail());
        user.setAccount(userInfo.getAccount());
        user.setPassword(userInfo.getPassword());
        //user.setIDCard();
        user.setPhone(userInfo.getPhone());
        user.setGender(userInfo.getGenderCode());
        Role role = roleDao.get(Role.class, userInfo.getRoleId());
        if (role == null) {
            return 0;
        }
        user.setRole(role);
        LocalDateTime localDateTime = LocalDateTime.parse(userInfo.getOnJobTime());
        if (localDateTime == null) {
            return 0;
        }
        user.setOnJobTime(localDateTime);
        userDao.update(user);
        return 1;
    }

    @Override
    public List<User> findUserAll() {
        logger.info("findUserAll");
        List<User> list = userDao.findAll();
        return list;
    }

    @Override
    public List<User> findUserAllPage(Page page) {
        logger.info("findUserAllPage");
        List<User> list = userDao.findAllByPage(page);
        return list;
    }

    @Override
    public List<User> findUserByRoleId(int roleId) {
        logger.info("findUserByRoleId:{}",roleId);
        return userDao.findByRoleId(roleId);
    }

    @Override
    public List<UserInfo> findAll() {
        logger.info("查询全部用户");
        List<User> users = userDao.findAll();
        List<UserInfo> userInfos = new ArrayList<>();
        for (User user : users) {
            userInfos.add(TransformUtil.fromUser(user));
        }
        return userInfos;
    }

    @Override
    public void updateUser(int userId, String userName, String userEmail, String userPhoneNumber) {
        logger.info("updateUser:userId={},userName={},userEmail={},userPhoneNumber={})",userId,userName,userEmail,userPhoneNumber);
        User user = userDao.get(User.class, userId);
        user.setName(userName);
        user.setEmail(userEmail);
        user.setPhone(userPhoneNumber);
        userDao.saveOrUpdate(user);
    }
    @Override
    public void updateUserInfo(MultipartFile fileField,String phone,String email,String dir) throws Exception{
        logger.info("updateUserInfo");
        Subject subject = SecurityUtils.getSubject();
        UserInfo userInfo = (UserInfo)subject.getSession().getAttribute(Constant.currentUserKey);
        if (!fileField.isEmpty()) {
            if (userInfo.getImgPath() != null) {
                File f = new File(dir, userInfo.getImgPath());
                if (f.exists()) f.delete();
            }
            String fileName = fileField.getOriginalFilename();
            try {
                byte[] bytes = fileField.getBytes();
                String newPath = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
                FileUtils.writeByteArrayToFile(new File(dir, newPath), fileField.getBytes());
                userDao.updateUser(userInfo.getId(), phone, email, newPath);
                userInfo.setImgPath(newPath);
                userInfo.setPhone(phone);
                userInfo.setEmail(email);
                subject.getSession().setAttribute(Constant.currentUserKey,userInfo);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception(e);
            }
        } else {
            throw new Exception();
        }
    }
}
